/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.j256.ormlite.demo.example;

import com.j256.ormlite.demo.ResourceTable;
import com.j256.ormlite.demo.slice.MainAbilitySlice2;

import ohos.agp.components.*;

import java.util.ArrayList;
import java.util.List;

/**
 * UserDaoAdapter
 *
 */
public class UserDaoAdapter extends BaseItemProvider {
    private MainAbilitySlice2 mainAbilitySlice;

    private List<UserBean> dataSet;

    /**
     * PeopleAdapter
     *
     * @param slice PersonAbilitySlice
     */
    public UserDaoAdapter(MainAbilitySlice2 slice) {
        mainAbilitySlice = slice;
        dataSet = new ArrayList<>();
    }

    /**
     * interface PersonClickListener
     *
     */
    public interface PersonClickListener {
        /**
         * onPersonClick
         *
         * @param position position
         */
        void onPersonClick(int position);
    }

    @Override
    public int getCount() {
        return dataSet.size();
    }

    @Override
    public Object getItem(int i) {
        return dataSet.get(i);
    }

    @Override
    public long getItemId(int id) {
        return id;
    }

    @Override
    public Component getComponent(int i, Component convertView, ComponentContainer componentContainer) {
        Component component = convertView;
        if (component == null) {
            component = LayoutScatter.getInstance(mainAbilitySlice)
                    .parse(ResourceTable.Layout_row_item_layout, null, false);
        }
        Text text = (Text) component.findComponentById(ResourceTable.Id_person_text);
        updateItem(i, text);
        return component;
    }

    private void updateItem(int position, Text text) {
        UserBean person = dataSet.get(position);
        text.setText(person.getId() + " " + person.getName() + " " + person.getLastName());
    }

    /**
     * setPeople
     *
     * @param queryResult queryresult
     */
    public void setPeople(List<UserBean> queryResult) {
        dataSet = queryResult;
        mainAbilitySlice.getUITaskDispatcher().asyncDispatch(() -> notifyDataChanged());
    }

    /**
     * setPeople
     *
     * @param iposition integer
     * @return userbean
     */
    public UserBean getPerson(int iposition) {
        return dataSet.get(iposition);
    }
}
